import {
	ACCESS_TOKEN
} from '@/store/mutation-types';

import * as API from '../../common/api';
import {
	logout
} from "../../common/api";

const loginSuccess = ({
	dispatch,
	commit
}, {
	token
}) => {
	uni.setStorageSync(ACCESS_TOKEN, token);
	commit('SET_TOKEN', token);
	setTimeout(() => {
		dispatch('GetInfo');
	}, 100)
};

const state = {
	token: '',
	userId: '',
	tenantId: ''
};



const mutations = {
	SET_TOKEN: (state, value) => {
		state.token = value;
	},
	SET_USER_ID: (state, value) => {
		state.userId = value;
	},
	SET_USER: (state, value) => {
		state.user = value;
	},
};

const actions = {
	async Login({
		dispatch,
		commit
	}, data) {
		try {
			const response = await API.login(data);
			const result = response.data;
			loginSuccess({
				dispatch,
				commit
			}, result);
			return response;
		} catch (error) {
			return Promise.reject(error);
		}
	},

	async GetInfo({
		commit
	}, data) {
		try {
			const res = await API.getInfo();
			const user = res.data.user;
			commit('SET_USER', user);
			commit('SET_USER_ID', user.userId);
			return res;

		} catch (error) {
			return Promise.reject(error);
		}
	},

	async Logout({
		commit
	}) {
		try {
			const res = await API.logout();
			uni.removeStorageSync(ACCESS_TOKEN);
			commit('SET_TOKEN', '');
			return res;

		} catch (error) {
			return Promise.reject(error);
		}

	},

};

export default {
	state,
	mutations,
	actions,
};